package com.tz.crm.components;

import org.apache.log4j.Logger;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;

/**
 * 实体拦截器 - 自动填充创建、更新时间
 *
 * @author HuJingling
 * @since 2017/1/19
 */
@Component
public class EntityInterceptor extends EmptyInterceptor {

    private static final Logger LOGGER = Logger.getLogger(EntityInterceptor.class);
    private static final long serialVersionUID = 7319416231145791577L;

    private static final String CREATE_DATE = "createDate"; // "创建日期"属性名称
    private static final String MODIFY_DATE = "modifyDate"; // "修改日期"属性名称

    /**
     * 空参构造
     */
    public EntityInterceptor() {
        LOGGER.debug("constructor...");
    }

    /**
     * 保存数据时回调此方法
     *
     * @param entity        Object
     * @param id            Serializable
     * @param state         Object[]
     * @param propertyNames propertyNames
     * @param types         types
     * @return boolean
     */
    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        LOGGER.trace("onSave...");
        Date createDate = new Date();
        for (int i = 0; i < propertyNames.length; i++) {
            if (CREATE_DATE.equals(propertyNames[i]) || MODIFY_DATE.equals(propertyNames[i])) {
                state[i] = createDate;
            }
        }
        return true;
    }


    /**
     * 更新数据时回调此方法
     */
    @Override
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState,
                                Object[] previousState, String[] propertyNames, Type[] types) {
        LOGGER.trace("onFlushDirty...");
        Date updateDate = new Date();
        for (int i = 0; i < propertyNames.length; i++) {
            if (MODIFY_DATE.equals(propertyNames[i])) {
                currentState[i] = updateDate;
            }
        }
        return true;
    }

}
